package com.xingfudazi.web.controller.app;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.extension.api.R;
import com.xingfudazi.app.domain.AppAccount;
import com.xingfudazi.app.domain.AppMember;
import com.xingfudazi.app.domain.AppMoment;
import com.xingfudazi.app.dto.MemberAvatar;
import com.xingfudazi.app.dto.WxRiskResponse;
import com.xingfudazi.app.service.*;
import com.xingfudazi.app.service.domain.WxRequestService;
import com.xingfudazi.common.annotation.Log;
import com.xingfudazi.common.core.controller.BaseController;
import com.xingfudazi.common.core.domain.AjaxResult;
import com.xingfudazi.common.core.domain.Result;
import com.xingfudazi.common.core.page.TableDataInfo;
import com.xingfudazi.common.enums.BusinessType;
import com.xingfudazi.common.utils.SecurityUtils;
import com.xingfudazi.common.utils.poi.ExcelUtil;
import com.xingfudazi.web.vo.AppMomentAvatarVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 动态Controller
 *
 * @author ruoyi
 * @date 2024-06-21
 */
@RestController
@RequestMapping("/app/moment")
public class AppMomentController extends BaseController {
    @Autowired
    private IAppMomentService appMomentService;

    @Autowired
    private IAppMemberInfoService appMemberInfoService;

    @Autowired
    private IAppFollowRelService appFollowRelService;

    @Autowired
    private IAppAccountService appAccountService;

    @Autowired
    private IAppMemberService appMemberService;

    @Autowired
    private WxRequestService wxRequestService;

    /**
     * 查询动态列表
     */
    @GetMapping("/turn")
    public Result<List<AppMomentAvatarVO>> turn(@RequestParam(defaultValue = "20") Integer pageSize,
                                                Long lastId, String search) {
        List<AppMoment> appMoments = appMomentService.turn(pageSize, lastId, search);

        if (appMoments.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 获取头像信息
        List<Long> nids = appMoments.stream().map(AppMoment::getNid).collect(Collectors.toList());


        // 获取用户信息
        Map<Long, MemberAvatar> memberAvatarMap = appMemberInfoService.queryMemberAvatar(nids).stream()
                .collect(Collectors.toMap(MemberAvatar::getNid, Function.identity()));

        // 获取是否关注
        Set<Long> fIds =  appFollowRelService.getFollowUserIds(SecurityUtils.getUserId(),nids);

        return Result.success(appMoments.stream().map(appMoment -> {
            AppMomentAvatarVO appMomentAvatarVO = new AppMomentAvatarVO();
            appMomentAvatarVO.setMoment(appMoment);
            appMomentAvatarVO.setMemberAvatar(memberAvatarMap.get(appMoment.getNid()));
            appMomentAvatarVO.setFollow(fIds.contains(appMoment.getNid()));
            return appMomentAvatarVO;
        }).collect(Collectors.toList()));

    }


    /**
     * 查询动态列表
     */
    @GetMapping("/list")
    public TableDataInfo list(AppMoment appMoment) {
        startPage();
        List<AppMoment> list = appMomentService.selectAppMomentList(appMoment);
        return getDataTable(list);
    }

    /**
     * 导出动态列表
     */
    @Log(title = "动态", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AppMoment appMoment) {
        List<AppMoment> list = appMomentService.selectAppMomentList(appMoment);
        ExcelUtil<AppMoment> util = new ExcelUtil<AppMoment>(AppMoment.class);
        util.exportExcel(response, list, "动态数据");
    }

    /**
     * 获取动态详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(appMomentService.selectAppMomentById(id));
    }

    /**
     * 新增动态
     */
    @Log(title = "动态", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppMoment appMoment) {
        Long userId = SecurityUtils.getUserId();

        AppMember appMember = appMemberService.getById(userId);
        Long aid = appMember.getAid();
        AppAccount appAccount = appAccountService.selectAppAccountById(aid);
        String openId = appAccount.getWxOpenId();
        Map<String, ?> res = (Map<String, ?>) wxRequestService.riskText(appMoment.getContent(), openId);

        if (checkRisk(res, appMoment.getContent())) {
            AjaxResult err = AjaxResult.error("当前用户名 内容存在风险");
            return err;
        }

        return toAjax(appMomentService.insertAppMoment(appMoment));
    }

    /**
     * 修改动态
     */
    @Log(title = "动态", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppMoment appMoment) {
        return toAjax(appMomentService.updateAppMoment(appMoment));
    }

//    @PostMapping("/test")
//    public Map<?, ?> uploadFileTest(String content) throws Exception {
//        System.out.print(content);
//        Map<?, ?> res = wxRequestService.riskImage2(content);
//        return res;
//    }

    private boolean checkRisk(Map<String, ?> response, String content) {
        if (content == null || content.isEmpty()) {
            return false;
        }

        Integer errorCode = (Integer) response.get("errcode");
        if (errorCode == null || errorCode != 0) {
            // Handle error code not being 0 or missing
            return true; // Assuming an error is considered a risk
        }

        @SuppressWarnings("unchecked")
        List<Map<String, ?>> detail = (List<Map<String, ?>>) response.get("detail");

        if (detail == null || detail.isEmpty()) {
            // No details provided, consider as no risk
            return false;
        }

        return detail.stream()
                .filter(item -> "content_model".equals(item.get("strategy")))
                .anyMatch(item -> {
                    Object labelObj = item.get("label");
                    return labelObj instanceof Integer && ((Integer) labelObj) != 100;
                });
    }
}
